package com.one.group.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.EasyExcel;
import com.one.group.admin.excel.VehicleData;
import com.one.group.admin.excel.VehicleDataReadListener;
import com.one.group.admin.mapper.ParkingSpaceMapper;
import com.one.group.enums.ErrorCode;
import com.one.group.model.dto.BaseDeleteDto;
import com.one.group.model.dto.VehicleAddDto;
import com.one.group.model.dto.VehicleQueryDto;
import com.one.group.model.entity.Vehicle;
import com.one.group.model.vo.VehicleListVo;
import com.one.group.model.vo.VehicleSearchVo;
import com.one.group.result.Result;
import com.one.group.service.VehicleService;
import com.one.group.utils.ResultUtil;
import com.one.group.utils.ThrowUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("vehicle")
@Tag(name = "车辆管理接口")
public class VehicleController {

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private ParkingSpaceMapper parkingSpaceMapper;

    /**
     * 查询车辆列表,需要和车位表连表查询
     * @param vehicleQueryDto
     * @return 车辆管理列表
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @Operation(summary = "车辆列表")
    public Result<PageInfo<VehicleListVo>> list(VehicleQueryDto vehicleQueryDto){
        //1.分页条件
        PageHelper.startPage(vehicleQueryDto.getPage(),vehicleQueryDto.getLimit());

        List<VehicleListVo> list = vehicleService.findVehicleByQueryDto(vehicleQueryDto);

        //3.分页结果
        PageInfo<VehicleListVo> pageInfo = new PageInfo<>(list);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 添加车辆
     * @param vehicleAddDto 车辆添加信息
     * @return 添加结果
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Operation(summary = "添加车辆")
    public Result<String> add(@Valid @RequestBody VehicleAddDto vehicleAddDto, BindingResult bindingResult) {
        //1.校验
        if(bindingResult.hasErrors()){
            List<ObjectError> errors = bindingResult.getAllErrors();
            StringBuilder sb = new StringBuilder();
            errors.forEach(objectError -> {
                String message = objectError.getDefaultMessage();
                sb.append(message).append(",");
            });
            return ResultUtil.error(ErrorCode.ADD_ERROR.getCode(),sb.toString());
        }
        boolean result = vehicleService.addVehicle(vehicleAddDto);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.ADD_ERROR.getCode(), "添加车辆失败");
        }
    }

    /**
     * 删除车辆
     * @param id 车辆ID
     * @return 删除结果
     */
    @GetMapping("/delete")
    @Operation(summary = "删除车辆")
    public Result<String> delete(Long id){
        ThrowUtil.throwIf(id==null, ErrorCode.PARAMS_ERROR);
        boolean result = vehicleService.deleteVehicle(id);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.DELETE_ERROR.getCode(), "删除车辆失败");
        }
    }

    /**
     * 批量删除车辆
     * @param baseDeleteDto 删除信息
     * @return 删除结果
     */
    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除车辆")
    public Result<String> deleteBatch(@RequestBody BaseDeleteDto baseDeleteDto) {
        ThrowUtil.throwIf(baseDeleteDto == null || baseDeleteDto.getIds() == null || baseDeleteDto.getIds().isEmpty(), 
                           ErrorCode.PARAMS_ERROR, "参数不能为空");
        boolean result = vehicleService.batchDeleteVehicles(baseDeleteDto.getIds());
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.DELETE_ERROR.getCode(), "批量删除车辆失败");
        }
    }

    /**
     * 修改车辆信息
     * @param vehicle 修改信息
     * @return 修改结果
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @Operation(summary = "修改车辆信息")
    public Result<String> update(@RequestBody Vehicle vehicle){
        //1.调用service进行修改
        boolean result = vehicleService.updateById(vehicle);
        //2.封装返回结果
        if(result){
            return ResultUtil.success();
        }
        return ResultUtil.error(ErrorCode.UPDATE_ERROR.getCode(), "修改车辆失败");
    }

    /**
     * 根据id查询车辆信息
     * @param id 车辆id
     * @return 车辆信息
     */
    @GetMapping("/findById")
    @Operation(summary = "根据id查询车辆信息")
    public Result<Vehicle> find(@RequestParam Long id){
        //1.参数校验
        ThrowUtil.throwIf(id == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtil.success(vehicleService.getById(id));
    }

    /**
     * 根据车牌号搜索车辆
     * @param plateNo 车牌号（支持模糊搜索）
     * @return 车辆搜索结果列表
     */
    @GetMapping("/search")
    @Operation(summary = "车辆搜索")
    public Result<List<VehicleSearchVo>> searchVehicles(@RequestParam String plateNo) {
        List<VehicleSearchVo> result = vehicleService.searchVehiclesByPlateNo(plateNo);
        return ResultUtil.success(result);
    }

    /**
     * 导入车辆信息
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/import")
    @Operation(summary = "导入车辆信息")
    public Result<String> importVehicles(@RequestParam("file") MultipartFile file) throws IOException{

            // 获取当前租户ID
            Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
            
            // 读取Excel文件
            EasyExcel.read(file.getInputStream(), VehicleData.class, 
                new VehicleDataReadListener(vehicleService, parkingSpaceMapper, tenantId))
                .sheet().doRead();
            
            return ResultUtil.success("导入成功");
    }

    /**
     * 导出车辆导入模板
     * @param response HTTP响应
     */
    @GetMapping("/exportTemplate")
    @Operation(summary = "导出车辆导入模板")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("车辆导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 创建示例数据
        List<VehicleData> list = new ArrayList<>();
        VehicleData data = new VehicleData();
        data.setPlateNo("京A12345");
        data.setCellName("示例小区");
        data.setOwnerName("张三");
        data.setContactPhone("13800138000");
        data.setOwnerTypeName("业主/租户/访客/其他");
        data.setRemark("示例备注");
        list.add(data);

        EasyExcel.write(response.getOutputStream(), VehicleData.class)
                .sheet("车辆导入模板")
                .doWrite(list);
    }
}
